package protocol;

import network.Send;
import utils.ByteUtils;
import utils.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Objects;

public class JodisSend implements Send {
    private Logger logger = Logger.getLogger(getClass());

    private boolean completed = false;

    private Response response;

    public JodisSend(Response response) {
        this.response = response;
    }

    @Override
    public int write(SocketChannel socketChannel) {
        int write = 0;
        try{
            if(Objects.isNull(response)){
                response = ErrorResponse.errorCommon();
            }
//            byte[] data = sb.toString().getBytes();
//            ByteBuffer buffer = ByteBuffer.allocate(data.length);
//            buffer.put(data);
//            buffer.flip();
            byte[] bytes = ByteUtils.getBytesUTF8(response.toRespString());
            //根据一个byte[]来生成一个固定的ByteBuffer时
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            write = socketChannel.write(buffer);
        }catch (IOException e){
            logger.error(e);
        }
        completed = true;
        return write;
    }

    @Override
    public boolean completed() {
        return this.completed;
    }
}
